import { app, BrowserWindow, ipcMain } from 'electron';
import * as path from 'path';

const dev = process.env.NODE_ENV === 'development';

export class ElectronService {
  onApplicationBootstrap() {
    if (dev && app) {
      app
        .whenReady()
        .then(this.createWindow)
        .catch(err => {});
      app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') {
          app.quit();
        }
      });
      ipcMain.on('play', this.handlePlay);
    }
  }

  handlePlay(event, arg) {
    event.reply('play', '--接受到信息--');
  }

  createWindow() {
    const mainWindow = new BrowserWindow({
      width: 600,
      height: 400,
      title: '课堂助手',
      show: false,
      webPreferences: {
        nodeIntegration: true,
        devTools: true,
        defaultEncoding: 'utf-8',
      },
    });
    mainWindow.once('ready-to-show', () => {
      mainWindow.show();
    });
    if (dev) {
      mainWindow.loadURL(`http://localhost:9123`);
    } else {
      const filePath = path.join(__dirname, '../frontend/index.html');
      mainWindow.loadURL(`file://${filePath}`);
    }
  }
}
